package com.pureut.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pureut.storage.domain.*;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.SalesReturnExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.SalesReturnDetailService;
import com.pureut.storage.service.SalesReturnService;
import com.pureut.storage.service.WarehouseService;
import com.pureut.storage.util.UnitUtil;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.vo.OrderReviewVo;
import com.pureut.storage.vo.PickingRestDbVo;
import com.pureut.storage.vo.SalesReturnVo;
import com.pureut.storage.vo.SalesVo;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.order.api.RemoteCustomerService;
import com.sale.order.api.RemoteSaleService;
import com.sale.order.api.dto.SaleServiceDto;
import com.sale.order.api.vo.SaleServiceVo;
import com.sale.system.api.*;
import com.sale.system.api.domain.SysAuxiliary;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.SysUser;
import com.sale.system.api.domain.dto.SysApiCategoryDto;
import com.sale.system.api.domain.dto.SysDocumentResultDto;
import com.sale.system.api.domain.dto.SysMaterialCodingResultDto;
import com.sale.system.api.domain.vo.SysAuditHistoryVo;
import com.sale.system.api.domain.vo.SysWorkbenchAuditAgentDubboVo;
import com.sale.system.api.model.MaterialUnitDto;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/***
 * 销售退货实现层
 * Author:C
 * Date:2022/12/29 11:12
 * @DESC
 */
@Service
@RequiredArgsConstructor
public class SalesReturnServiceImpl implements SalesReturnService {


    private final SalesReturnMapper salesReturnMapper;


    private final WarehouseService warehouseService;


    private final SalesReturnDetailService salesReturnDetailService;


    private final SalesReturnDetailMapper salesReturnDetailMapper;


    private final WmsStockInfoMapper wmsStockInfoMapper;

    private final OutboundLogMapper outboundLogMapper;

    private final PickingSaleMapper pickingSaleMapper;


    //用户信息
    @DubboReference
    RemoteUserService remoteUserService;

    @DubboReference
    RemoteReviewService remoteReviewService;


    /**
     * 单位服务
     */
    @DubboReference
    RemoteUnitService remoteUnitService;

    /**
     * 编码生成服务
     */
    @DubboReference
    RemoteCodeService remoteCodeService;

    /**
     * 菜单服务
     */
    @DubboReference
    RemoteMenuService remoteMenuService;

    /**
     * 单据配置服务
     */
    @DubboReference
    RemoteDocumentService remoteDocumentService;

    /**
     * 单据配置服务
     */
    @DubboReference
    RemoteCodingService remoteCodingService;

    /**
     * 客户服务
     */
    @DubboReference
    RemoteSysCustomerService remoteSysCustomerService;

    private final PickingSaleDetailMapper pickingSaleDetailMapper;

    @DubboReference
    RemoteWorkbenchMessageService remoteWorkbenchMessageService;

    @DubboReference
    RemoteSaleService remoteSaleService;

    @Resource
    UnitUtil unitUtil;


    /**
     * 销售退货列表
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public TableDataInfo<SalesReturnDto> getSalesList(SalesReturnVo salesReturnVo, PageQuery pageQuery) throws Exception {
        Page<SalesReturnDto> saleList = salesReturnMapper.getSaleList(pageQuery.build(), salesReturnVo);
        List<SalesReturnDto> records = saleList.getRecords();

        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();
        //获取销售退货状态字典值
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_return_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //收发类型
        List<SysDictData> rdTypeArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_return_rd_type");
        Map<String, String> rdTypeMap = rdTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //客户
        Map<String, String> customerMap = remoteSysCustomerService.getOpenCustomerFinance();
        for (SalesReturnDto entity : records) {
            //手法类型
            entity.setReceiveTypeDict(rdTypeMap.get(entity.getReceiveType()));
            //客户
            entity.setCustomerName(entity.getCustomerName());
            //辅助属性
            List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
            entity.setAuxiliaryAttribute(statsArray);
            //状态
            entity.setStatusDict(statusMap.get(entity.getStatus()));
            //单据类型
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(entity.getDocumentType())));
            //生成方式
            entity.setGenerationMethodDict(GenerationMethodEnum.getValue(Integer.parseInt(entity.getGenerationMethod())));
            //单位
            entity.setUnitDict(unitByCodeToMap.get(entity.getMaterialUnit()).getUnitName());
//            if (entity.getMaterialMoreUnit() != null) {
//                //转换
//                UnitConversionDto unitConversionDto = unitUtil.atWillunitConversion(entity.getMaterialUnit(), entity.getMaterialCode(),
//                    String.valueOf(entity.getBackWeight()), entity.getMaterialId());
//
//                if (unitConversionDto != null) {
//                    entity.setUnitConversion(unitConversionDto.getMaterialMoreUnitNumber());
//                }
//            }
            //单位转换
            String s = unitUtil.unitC(entity.getMaterialCode(),
                String.valueOf(entity.getBackWeight()),
                entity.getMaterialId(),
                unitByCodeToMap.get(entity.getMaterialUnit()).getUnitName());
            entity.setUnitConversion(s);

        }
        return TableDataInfo.build(saleList);
    }

    /**
     * 销售退货新增
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public boolean addSalesReceipt(SalesReturnVo salesReturnVo) throws Exception {
        List<SalesVo> salesList = salesReturnVo.getSalesList();
        if (salesList.size() == 0) {
            throw new GlobalException("至少存在一条数据");
        }
        List<SalesReturn> salesReturnList = new ArrayList<>();
        for (SalesVo entity : salesList) {
            SalesReturn salesReturn = new SalesReturn();
            String authorityCoding = remoteCodeService.authorityCoding("warehouse:warehousing:saleReturn:list");
            if (authorityCoding == null) {
                throw new GlobalException("该单据未进行配置，无法生成单据编码");
            }
            //获取销售订单单价
//            PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>()
//                .lambda().eq(PickingSale::getWodDocNum, entity.getSaleOrderNo()));
            //通过物料编码及销售订单号获取对应的单价
//            String materialCode = pickingSale.getMaterialCode();
//            String connectionId = pickingSale.getConnectionId();
//            SaleServiceVo saleServiceVo = new SaleServiceVo();
//            saleServiceVo.setSalesOrderNum(connectionId);
//            saleServiceVo.setMaterialCode(materialCode);
//            SaleServiceDto salePlace = remoteSaleService.getSalePlace(saleServiceVo);
            salesReturn.setReceiptNo(authorityCoding)
                .setDeptId(LoginHelper.getDeptId())
                .setStatus(1)
                .setSaleOrderNo(entity.getSaleOrderNo())
                .setWarehousTime(salesReturnVo.getWarehousTime())
                .setMaterialCode(entity.getMaterialCode())
                .setCustomerCode(salesReturnVo.getCustomerCode())
                .setBackWeight(entity.getBackWeight())
                .setShippedWeight(entity.getShippedWeight())
                .setWarehousingWarehouse(entity.getWarehousingWarehouse())
                .setDocumentType(DocumentTypeEnum.SALES_RETURN.getCode())
                .setGenerationMethod(GenerationMethodEnum.MANUALLY_GENERATED.getCode())
                .setRemark(salesReturnVo.getRemark())
                .setMaterialUnit(entity.getMaterialUnit())
                .setCreateTime(new Date())
                .setDrawerBy(LoginHelper.getUsername())
                .setReceiveType(salesReturnVo.getReceiveType())
//                .setUnitPrice(salePlace.getUnitPrice())
                .setDrawerTime(salesReturnVo.getWarehousTime());
            salesReturnList.add(salesReturn);
        }
        return salesReturnMapper.insertBatch(salesReturnList);
    }

    /**
     * 关结
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public boolean close(SalesReturnVo salesReturnVo) {
        SalesReturn salesReturn = salesReturnMapper.selectById(salesReturnVo.getId());

        //已完成、已关结不可重复关结；
        if (salesReturn.getStatus() != 5 && salesReturn.getStatus() != 6) {
            //仅【待提交  待审核     未通过  审核中  待入库   入库中  待交接】状态的单据进行关结
            //1、待提交、待审核、未通过、审核中、待入库、入库中状态的单据关结后，单据状态变为"已关结"
            boolean statusValue = salesReturn.getStatus() == 1
                || salesReturn.getStatus() == 2
                || salesReturn.getStatus() == 3
                || salesReturn.getStatus() == 4;
            if (statusValue) {
                salesReturn.setStatus(6)
                    .setCloseReason(salesReturnVo.getCloseReason())
                    .setClosingBy(LoginHelper.getUsername())
                    .setClosingTime(new Date());
            }
            //2、"待交接"的单据关结后，单据状态变为"已关结"，单据明细的物料状态变为已入库
            if (salesReturn.getStatus() == 4) {
                salesReturn.setStatus(6)
                    .setCloseReason(salesReturnVo.getCloseReason())
                    .setClosingBy(LoginHelper.getUsername())
                    .setClosingTime(new Date());
                List<SalesReturnDetail> salesReturnDetails = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda()
                    .eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
                for (SalesReturnDetail entity : salesReturnDetails) {
                    entity.setStatus(3);
                }
                salesReturnDetailMapper.updateBatchById(salesReturnDetails);
            }
        } else {
            throw new GlobalException("已完成、已关结不可重复关结");
        }
        return salesReturnMapper.updateById(salesReturn) > 0;


    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public SalesReturnDto getView(Long id) {

        SalesReturnDto saleById = salesReturnMapper.getSaleById(id);
        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();
        //单据类型
        saleById.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(saleById.getDocumentType())));

        //收发类型
        List<SysDictData> rdTypeArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_return_rd_type");
        Map<String, String> rdTypeMap = rdTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        //列表
        List<ViewDto> viewDtos = new ArrayList<>();
        ViewDto viewDto = new ViewDto();
        viewDto.setSaleOrderNo(saleById.getSaleOrderNo());
        viewDto.setShippedWeight(saleById.getShippedWeight());
        viewDto.setBackWeight(saleById.getBackWeight());
        viewDto.setMaterialName(saleById.getMaterialName());
        viewDto.setMaterialCode(saleById.getMaterialCode());
        viewDto.setMaterialSpec(saleById.getMaterialSpec());
        viewDto.setMaterialUnit(saleById.getMaterialUnit());
        viewDto.setUnitDict(unitByCodeToMap.get(saleById.getMaterialUnit()).getUnitName());
        //辅助属性
        List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + saleById.getTenantId(), String.valueOf(saleById.getMaterialId()));
        viewDto.setAuxiliaryAttribute(statsArray);

        //入库仓
        WarehouseDto view = warehouseService.getView(saleById.getWarehousingWarehouse());
        if (view != null) {
            viewDto.setWarehousingWarehouse(String.valueOf(saleById.getWarehousingWarehouse()));
            viewDto.setWarehouseName(view.getWarehouseName());
        }
        viewDtos.add(viewDto);
        saleById.setViewList(viewDtos);
        //收发类型
        saleById.setReceiveTypeDict(rdTypeMap.get(saleById.getReceiveType()));
        return saleById;
    }


    /**
     * 修改
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public boolean updateSalesReceipt(SalesReturnVo salesReturnVo) {
        SalesReturn salesReturn = salesReturnMapper.selectById(salesReturnVo.getId());
        if (salesReturn.getStatus() == 1 || salesReturn.getStatus() == 4) {
            salesReturn.setDrawerTime(salesReturnVo.getDrawerTime());
            salesReturn.setCustomerCode(salesReturnVo.getCustomerCode());
            salesReturn.setWarehousTime(salesReturnVo.getWarehousTime());
            salesReturn.setRemark(salesReturnVo.getRemark());
            List<SalesVo> salesList = salesReturnVo.getSalesList();
            for (SalesVo entity : salesList) {
                salesReturn
                    .setMaterialCode(entity.getMaterialCode())
                    .setMaterialUnit(entity.getMaterialUnit())
                    .setSaleOrderNo(entity.getSaleOrderNo())
                    .setBackWeight(entity.getBackWeight())
                    .setWarehousingWarehouse(entity.getWarehousingWarehouse());
            }
            //调用审核
            if (salesReturn.getStatus() == 4) {
                SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
                String perms = "warehouse:warehousing:saleReturn:review";
                String auditDoc = salesReturn.getReceiptNo();
                sysAuditHistoryVo.setAuditDoc(auditDoc);
                sysAuditHistoryVo.setPerms(perms);
                int i = remoteReviewService.editHistory(sysAuditHistoryVo);
                if (i > 0) {
                    salesReturn.setStatus(1);
                    //修改审核代办状态为已处理
                    remoteWorkbenchMessageService.updateStatus(3, salesReturn.getReceiptNo(), "销售退货");
                    return salesReturnMapper.updateById(salesReturn) > 0;
                } else {
                    return false;
                }
            }
            //修改审核代办状态为已处理
            remoteWorkbenchMessageService.updateStatus(3, salesReturn.getReceiptNo(), "销售退货");

            return salesReturnMapper.updateById(salesReturn) > 0;
        } else {
            throw new GlobalException("只能修改待提交和未通过的数据");
        }
    }

    /**
     * 删除
     *
     * @param idStr
     * @return
     */
    @Override
    public boolean deleteSalesReceipt(String idStr) {
        List<String> idList = Arrays.asList(idStr.split(","));
        if (idList.size() == 0) {
            throw new GlobalException("至少勾选一条数据");
        }
        List<SalesReturn> salesReturns = new ArrayList<>();
        List<SalesReturn> salesReturnList = salesReturnMapper.selectList(new QueryWrapper<SalesReturn>().lambda().in(SalesReturn::getId, idList));
        for (SalesReturn entity : salesReturnList) {
            if (entity.getStatus() == 1 || entity.getStatus() == 4) {
                salesReturns.add(entity);
            } else {
                throw new GlobalException("只能删除待提交或者未通过的单据");
            }
        }
        List<SalesReturn> deleteList = new ArrayList<>();
        for (SalesReturn entity : salesReturns) {
            if (entity.getGenerationMethod() == 2) {
                deleteList.add(entity);
            } else {
                throw new GlobalException("自动生成的单据不能删除");
            }
        }
        for (SalesReturn entity : deleteList) {
            remoteWorkbenchMessageService.deleteDoc(entity.getReceiptNo(), "销售退货");
        }
        return salesReturnMapper.deleteBatchIds(deleteList) > 0;
    }

    /**
     * 导出
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public List<SalesReturnExport> getInfoExport(SalesReturnVo salesReturnVo) {
        List<SalesReturnExportDto> salesReturnList = null;

        if (salesReturnVo.getIdStr() == null) {
            salesReturnList = salesReturnMapper.getSaleListOut(salesReturnVo);
        } else {
            List<String> idList = Arrays.asList(salesReturnVo.getIdStr().split(","));
            //获取销售退货列表
            salesReturnList = salesReturnMapper.getDataByIdStr(idList);
        }
//        //获取网型标准缓存字典数据
//        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
//        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//        //获取铺网类型标准缓存字典数据
//        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
//        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//
//        //销售退货收发类型字典数据
//        List<SysDictData> rdArray = DictUtils.getDictCache("sales_return_rd_type");
//        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SalesReturnExport> salesReturnExportList = new ArrayList<>();
        for (SalesReturnExportDto entity : salesReturnList) {
            SalesReturnExport salesReturnExport = new SalesReturnExport();

            BeanUtils.copyProperties(entity, salesReturnExport);

//            salesReturnExport.setMaterialNetDict(netMap.get(entity.getMaterialNetDict()));
//            salesReturnExport.setMaterialNetTypeDict(netTypeMap.get(entity.getMaterialNetTypeDict()));
            salesReturnExportList.add(salesReturnExport);
        }
        return salesReturnExportList;
    }


    /**
     * 销售退货pda
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto salesReturnPda(PickingRestDbVo pickingRestDbVo) throws Exception {
        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();
        SalesReturn salesReturn = salesReturnMapper.selectById(pickingRestDbVo.getId());
//        if (salesReturn.getStatus() == 5 || salesReturn.getStatus() == 7 || salesReturn.getStatus() == 6) {
            if (salesReturn.getStatus() == 1 || salesReturn.getStatus() == 2 ) {
            //扫码入库
            if ("1".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("没有该仓库信息，请核实!");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setMessage("操作成功");
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据物料号码查询销售发货（出库模块）明细信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    //获取明细对象
//                    SalesReturnDetail salesReturnDetailObject = pickingRestDbVo.getSalesReturnObject();
//                    PickingSaleDetail pickingSaleDetail = pickingSaleDetailMapper.selectOne(new QueryWrapper<PickingSaleDetail>()
//                        .lambda().eq(PickingSaleDetail::getPdoductNumber, pickingRestDbVo.getInputValue()));
                    OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>()
                        .lambda().eq(OutboundLog::getWsiMaterialNumber, pickingRestDbVo.getInputValue()));
                    if (outboundLog == null) {
                        pickingRestDbDto.setCode("500");
                        pickingRestDbDto.setMessage("没有查询到对应物料，请核实后输入!");
                        return pickingRestDbDto;
                    }

                    //查询该物料是否入库过
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>()
                        .lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()));

                    if (wmsStockInfo != null) {
                        pickingRestDbDto.setMessage("该数据已经入库");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }

                    //获取单据配置信息
                    Long menuId = remoteMenuService.getIdByMenuName("销售退货");
                    SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

                    if (sysDocument == null) {
                        throw new GlobalException("未获取到单据配置信息");
                    }

                    SalesReturnDetail salesReturnDetail = new SalesReturnDetail();
                    //单位
                    MaterialUnitDto data1 = remoteUnitService.getUnitDataByCode(Long.parseLong(salesReturn.getMaterialUnit())).getData();
                    //获取物料类别信息
//                    SysApiCategoryDto data = remoteCodingService.getByCode(pickingSaleDetail.getItemCode()).getData();


                    //根据扫描的物料编码和入库列表数据进行比对
//                    for (SalesReturnDto entity : saleList) {
                    //如果对应的编码相等，就将该明细存入
                    if (salesReturn.getMaterialCode().equals(outboundLog.getWsiMaterialCode())) {

                        salesReturnDetail.setSalesReturnId(salesReturn.getId());
                        salesReturnDetail.setMaterialCode(outboundLog.getWsiMaterialCode());
                        salesReturnDetail.setMaterialNumber(pickingRestDbVo.getInputValue());
                        salesReturnDetail.setGrossWeight(outboundLog.getWsiGorssWeight());
                        salesReturnDetail.setNetWeight(outboundLog.getWsiNetWeight());
                        salesReturnDetail.setReceiptQuantity(1);
                        salesReturnDetail.setBatchNo(outboundLog.getWsiMaterialBatch());
                        salesReturnDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                        salesReturnDetail.setWarehouseInBy(LoginHelper.getUsername());
                        salesReturnDetail.setMaterialUnit(salesReturn.getMaterialUnit());
                        salesReturnDetail.setWarehouseInTime(new Date());


                        //向仓库表中添加对应的数据
                        WmsStockInfo wmsStockInfo1 = new WmsStockInfo();
                        BeanUtils.copyProperties(outboundLog, wmsStockInfo1, new String[]{"id"});

                        wmsStockInfo1.setWsiMaterialStatus(2);
                        if (data1.getUnitQuantity() != null) {
                            wmsStockInfo1.setWsiMinunitNum(Integer.parseInt(data1.getUnitQuantity()));
                        }

                        wmsStockInfoMapper.insert(wmsStockInfo1);

                    } else {
                        pickingRestDbDto.setMessage("入库物料和单据物料不一致，无法入库");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }

                    //添加重量
                    if (salesReturn.getActualQuantity() == null || "".equals(salesReturn.getActualQuantity())) {
                        salesReturn.setActualQuantity(String.valueOf(salesReturnDetail.getNetWeight()));
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(salesReturn.getActualQuantity());
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                        String s = bigDecimal.add(bigDecimal1).toString();
                        salesReturn.setActualQuantity(s);
                    }
                    if (salesReturn.getWarehousingNum() == 0) {
                        salesReturn.setWarehousingNum(1);
                    } else {
                        salesReturn.setWarehousingNum(salesReturn.getWarehousingNum() + 1);
                    }


                    pickingRestDbDto.setQuantityIdentification(salesReturn.getBackWeight() + "/" + salesReturn.getActualQuantity() + data1.getUnitName());
                    pickingRestDbDto.setMessage("物料号码:" + pickingRestDbVo.getInputValue() + "," + "数量:" + "1" + "," + "录入成功");

                    pickingRestDbDto.setUnitDict(data1.getUnitName());
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(salesReturn.getWarehousingNum()));


                    double aDouble = Double.parseDouble(salesReturn.getActualQuantity());
                    double backWeight = salesReturn.getBackWeight();

                    //判断是否配置了超收
                    if (sysDocument.getDocExcessMark() == 2) {
                        if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(backWeight)) {
                            //如果配置了交接
                            if (sysDocument.getDocHandoverMark() == 1) {
                                salesReturn.setStatus(4);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为待交接
                                salesReturnDetail.setStatus(2);
                            } else {
                                salesReturn.setStatus(5);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为已入库
                                salesReturnDetail.setStatus(3);
                            }
                        } else {
                            //如果配置了交接
                            if (sysDocument.getDocHandoverMark() == 1) {
                                salesReturn.setStatus(4);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为待交接
                                salesReturnDetail.setStatus(2);
                            } else {
                                salesReturn.setStatus(2);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为已入库
                                salesReturnDetail.setStatus(3);
                            }
                        }
                    } else {
                        if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(backWeight)) {
                            //如果配置了交接
                            if (sysDocument.getDocHandoverMark() == 1) {
                                salesReturn.setStatus(4);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为待交接
                                salesReturnDetail.setStatus(2);
                            } else {
                                salesReturn.setStatus(2);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为已入库
                                salesReturnDetail.setStatus(3);
                            }
                        } else {
                            //如果配置了交接
                            if (sysDocument.getDocHandoverMark() == 1) {
                                salesReturn.setStatus(4);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为待交接
                                salesReturnDetail.setStatus(2);
                            } else {
                                salesReturn.setStatus(2);
                                salesReturnMapper.updateById(salesReturn);
                                //设置明细状态为已入库
                                salesReturnDetail.setStatus(3);
                            }
                        }
                    }
                    salesReturnDetailMapper.insert(salesReturnDetail);
                    //回传销售退货
//                    BackDataVo backDataVo = new BackDataVo();
//                    PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>().lambda().eq(PickingSale::getWodDocNum, byId.getSaleOrderNo()));
//                    backDataVo.setSaleNumber(pickingSale.getConnectionId());
//                    backDataVo.setMaterialCode(byId.getMaterialCode());
//                    backDataVo.setNetWeight(pickingSaleDetail.getNetWeight());
//                    boolean b = orderFeignService.updateShippingOutWeight(backDataVo);
//                    if (!b) {
//                        throw new GlobalException("服务调用失败");
//                    }

//                    salesReturn.setStatus(7);
                    salesReturnMapper.updateById(salesReturn);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }


            }
            //条码撤销
            if ("2".equals(pickingRestDbVo.getType())) {
//                //如果是第一步，需要查询库位信息
//                if (pickingRestDbVo.getExecutionOrder() == 1) {
//                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
//                    if (warehouseCode.getCombinationName() == null) {
//                        pickingRestDbDto.setMessage("没有该仓库信息，请核实!");
//                        pickingRestDbDto.setCode("500");
//                        return pickingRestDbDto;
//                    }
//                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
//                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
//                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
//                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
//                    pickingRestDbDto.setMessage("操作成功");
//                    pickingRestDbDto.setCode("200");
//                    return pickingRestDbDto;
//                }
                //如果是第二步，需要根据物料号码查询明细信息
//                if (pickingRestDbVo.getExecutionOrder() == 2) {
                //查询该条码是否扫描过
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()));
                if (wmsStockInfo == null) {
                    pickingRestDbDto.setMessage("撤销失败，请核实后再录入");
                    pickingRestDbDto.setCode("500");
                    return pickingRestDbDto;
                }
                wmsStockInfoMapper.deleteById(wmsStockInfo);

                //同时删除采购入库明细状态
                SalesReturnDetail salesReturnDetail = salesReturnDetailMapper.selectOne(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                //单位
                String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(salesReturn.getMaterialUnit())).getData().getUnitName();

                //设置返回信息
                pickingRestDbDto.setMessage("物料号码:" + salesReturnDetail.getMaterialNumber() + "," + "数量:" + salesReturnDetail.getReceiptQuantity() + "," + "撤销成功");
                pickingRestDbDto.setQuantityIdentification(salesReturn.getBackWeight() + "/" + salesReturn.getActualQuantity() + unitName);
//                pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                pickingRestDbDto.setUnitDict(unitName);
                pickingRestDbDto.setWarehouseNumber(String.valueOf(salesReturn.getWarehousingNum()));

                salesReturnDetailMapper.deleteById(salesReturnDetail);
                List<SalesReturnDetail> list = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>()
                    .lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
                //判断条数修改采购入库状态
                if (list.size() == 0) {
                    salesReturn.setStatus(5);
                    salesReturn.setWarehousingNum(0);
                    salesReturn.setWarehousingWeight(0);
                    salesReturn.setActualQuantity("0");
                } else {
                    //判断单位
                    BigDecimal bigDecimal = new BigDecimal(salesReturn.getActualQuantity());
                    BigDecimal bigDecimal1;
                    //如果是千克
                    bigDecimal1 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                    String s = bigDecimal.subtract(bigDecimal1).toString();
                    salesReturn.setActualQuantity(s);


                    //回传销售退货
//                    BackDataVo backDataVo = new BackDataVo();
//                    PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>().lambda().eq(PickingSale::getWodDocNum, salesReturn.getSaleOrderNo()));
//                    backDataVo.setSaleNumber(pickingSale.getConnectionId());
//                    backDataVo.setMaterialCode(salesReturn.getMaterialCode());
//                    backDataVo.setNetWeight(salesReturnDetail.getNetWeight());
//                    boolean b = orderFeignService.updateShippingOutWeight(backDataVo);
//                    if (!b) {
//                        throw new GlobalException("服务调用失败");
//                    }

                }
                salesReturnMapper.updateById(salesReturn);
                pickingRestDbDto.setCode("200");
                return pickingRestDbDto;
//                }
            }
        } else {
            pickingRestDbDto.setMessage("只能操作待入库和入库中得数据");
            pickingRestDbDto.setCode("500");
            return pickingRestDbDto;
        }
        pickingRestDbDto.setMessage("步骤不正确,请核实!");
        pickingRestDbDto.setCode("500");
        return pickingRestDbDto;
    }

    /**
     * 销售退货拣货撤销
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCancellation(PickingRestDbVo pickingRestDbVo) {
        //根据其它入库id获取明细数据
        List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
        //根据批次号查询仓库信息
        List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, salesReturnDetailList.get(0).getBatchNo()));
        //删除仓储数据
        wmsStockInfoMapper.deleteBatchIds(wmsStockInfoList);
        //删除明细数据
        salesReturnDetailMapper.deleteBatchIds(salesReturnDetailList);
        //修改销售退货状态
        SalesReturn salesReturn = salesReturnMapper.selectById(pickingRestDbVo.getId());
        salesReturn.setStatus(1);
        salesReturn.setWarehousingNum(0);
        salesReturn.setWarehousingWeight(0);
        salesReturn.setActualQuantity("0");
        return salesReturnMapper.updateById(salesReturn) > 0;
    }

    /**
     * 销售退货拣货完成
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCompleted(PickingRestDbVo pickingRestDbVo) throws Exception {
        SalesReturn salesReturn = salesReturnMapper.selectById(pickingRestDbVo.getId());
        if (salesReturn.getStatus() == 8) {
            throw new GlobalException("不能对已完成的单据进行拣货完成");
        }

        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("销售退货");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        if (sysDocument == null) {
            throw new GlobalException("未获取到单据配置信息");
        }
        //是否配置交接
        if (sysDocument.getDocHandoverMark() == 1) {
            salesReturn.setStatus(6);
        } else {
            salesReturn.setStatus(8);
        }
        return salesReturnMapper.updateById(salesReturn) > 0;
    }

    /**
     * 销售退货交接
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestHandoverDto handover(PickingRestDbVo pickingRestDbVo) {
        PickingRestHandoverDto pickingRestHandoverDto = new PickingRestHandoverDto();

        SalesReturn salesReturn = salesReturnMapper.selectById(pickingRestDbVo.getId());
        if (salesReturn.getStatus() != 4) {
            pickingRestHandoverDto.setResultCode("500");
            pickingRestHandoverDto.setMessage("只能操作待交接的单据");
            return pickingRestHandoverDto;
        }
        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("销售退货");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        if (sysDocument == null) {
            throw new GlobalException("未获取到单据配置信息");
        }
        //第一步根据工号查询交接人
        if (pickingRestDbVo.getExecutionOrder() == 1) {
            //校验员工编号
            String userName = pickingRestDbVo.getInputValue();
            SysUser sysUser = remoteUserService.getByUserName(userName).getData();

            if (sysUser.getUserName() == null) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                return pickingRestHandoverDto;
            }

            //单位
            String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(salesReturn.getMaterialUnit())).getData().getUnitName();

            //如果是整单
            if ("3".equals(sysDocument.getDocHandoverMethod())) {
                BigDecimal bigDecimalNetWeight = new BigDecimal(0);
                //根据id获取明细信息
                List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
                if (salesReturnDetailList.size() != 0) {
                    for (SalesReturnDetail entity : salesReturnDetailList) {
                        entity.setStatus(3);
                        bigDecimalNetWeight = bigDecimalNetWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                    }
                    salesReturnDetailMapper.updateBatchById(salesReturnDetailList);
                    //修改销售退货状态为已经完成
                    salesReturn.setStatus(5);
                    salesReturn.setHandoverWeight(Double.parseDouble(bigDecimalNetWeight.toString()));
                    salesReturn.setHandoverNum(salesReturnDetailList.size());
                    salesReturnMapper.updateById(salesReturn);
                } else {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("该单据下无交接的明细数据，请核实");
                    return pickingRestHandoverDto;
                }


                //设置出参数据
                pickingRestHandoverDto.setQuantityIdentification(salesReturn.getWarehousingWeight() + "/" + bigDecimalNetWeight + unitName);
                pickingRestHandoverDto.setOutHandoverActual(salesReturnDetailList.size() + "/" + salesReturnDetailList.size());
                pickingRestHandoverDto.setMessage("单据号:" + salesReturn.getReceiptNo() + "," + "数量:" + salesReturnDetailList.size() + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }

        }

        //批次
        if ("2".equals(sysDocument.getDocHandoverMethod())) {
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                SysUser sysUser = remoteUserService.getByUserName(userName).getData();

                if (sysUser.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(sysUser.getUserName() + "-" + sysUser.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(Integer.parseInt(sysDocument.getDocHandoverMethod()));
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
            if (pickingRestDbVo.getExecutionOrder() == 2) {
                //通过批次号查询明细数据
                List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getBatchNo, pickingRestDbVo.getInputValue()));
                //单位
                String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(salesReturn.getMaterialUnit())).getData().getUnitName();

                if (salesReturnDetailList.size() > 0) {
                    BigDecimal bigDecimalHand = new BigDecimal(0);
                    for (SalesReturnDetail entity : salesReturnDetailList) {
                        entity.setStatus(3);
                        bigDecimalHand = bigDecimalHand.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                    }
                    salesReturnDetailMapper.updateBatchById(salesReturnDetailList);
                    //修改仓库表数据
                    List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, pickingRestDbVo.getInputValue()));
                    for (WmsStockInfo info : wmsStockInfoList) {
                        info.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoMapper.updateBatchById(wmsStockInfoList);
                    //交接重量
                    BigDecimal handoverWeight = bigDecimalHand.add(new BigDecimal(String.valueOf(salesReturn.getHandoverWeight())));

                    //交接数量
                    BigDecimal handoverNum = new BigDecimal(salesReturnDetailList.size()).add(new BigDecimal(salesReturn.getHandoverNum()));
                    //入库数量
                    List<SalesReturnDetail> detailListById = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
                    boolean isTrue = true;
                    for (SalesReturnDetail entity : salesReturnDetailList) {
                        if (entity.getStatus() != 3) {
                            isTrue = false;
                            break;
                        }
                    }
                    //如果明细都是已完成，就修改状态为已完成
                    if (isTrue) {
                        salesReturn.setStatus(5);
                    }
                    salesReturn.setHandoverWeight(Double.parseDouble(handoverWeight.toString()));
                    salesReturn.setHandoverNum(Integer.parseInt(handoverNum.toString()));
                    salesReturnMapper.updateById(salesReturn);

                    //设置出参内容
                    pickingRestHandoverDto.setQuantityIdentification(salesReturn.getWarehousingWeight() + "/" + handoverWeight + unitName);
                    pickingRestHandoverDto.setOutHandoverActual(detailListById.size() + "/" + handoverNum);
                    pickingRestHandoverDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + "," + "数量:" + salesReturnDetailList.size() + "," + "交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                    return pickingRestHandoverDto;

                } else {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("没有该批次号的数据，请核实后再操作");
                    return pickingRestHandoverDto;
                }
            }
        }
        //单个物料
        if ("1".equals(sysDocument.getDocHandoverMethod())) {
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                SysUser sysUser = remoteUserService.getByUserName(userName).getData();

                if (sysUser.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(sysUser.getUserName() + "-" + sysUser.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(Integer.parseInt(sysDocument.getDocHandoverMethod()));
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
            if (pickingRestDbVo.getExecutionOrder() == 2) {
                //交接数量
                //BigDecimal handoverNum = new BigDecimal(1).add(new BigDecimal(pickingRestDbVo.getHandoverNum()));

                //根据物料条码获取明细信息
                SalesReturnDetail salesReturnDetail = salesReturnDetailMapper.selectOne(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                //单位
                String unitName = remoteUnitService.getUnitDataByCode(Long.parseLong(salesReturn.getMaterialUnit())).getData().getUnitName();

                if (salesReturnDetail == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("只能操作待交接的单据");
                    return pickingRestHandoverDto;
                }
                //修改该明细状态为已经完成
                salesReturnDetail.setStatus(3);
                salesReturnDetailMapper.updateById(salesReturnDetail);
                //修改仓库表数据
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, salesReturnDetail.getMaterialNumber()));
                wmsStockInfo.setWsiMaterialStatus(2);
                wmsStockInfoMapper.updateById(wmsStockInfo);
                //交接重量
                //BigDecimal handoverWeight = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight())).add(new BigDecimal(String.valueOf(salesReturn.getHandoverWeight())));
                //判断明细是否都已经交接成功
                List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
                boolean isTrue = true;
                for (SalesReturnDetail entity : salesReturnDetailList) {
                    if (entity.getStatus() != 3) {
                        isTrue = false;
                        break;
                    }
                }
                //如果明细都是已完成，就修改其他入库为已完成
                if (isTrue) {
                    salesReturn.setStatus(5);
                }
//                salesReturn.setHandoverWeight(Double.parseDouble(handoverWeight.toString()));
//                salesReturn.setHandoverNum(Integer.parseInt(handoverNum.toString()));
                salesReturnMapper.updateById(salesReturn);

                //设置出参内容
                pickingRestHandoverDto.setQuantityIdentification(salesReturn.getWarehousingWeight() + "/" + 1 + unitName);
                pickingRestHandoverDto.setOutHandoverActual(salesReturnDetailList.size() + "/" + 1);
                pickingRestHandoverDto.setMessage("物料号码:" + salesReturnDetail.getMaterialNumber() + "," + "数量:" + 1 + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
        }

//            } else {
//                pickingRestHandoverDto.setResultCode("500");
//                pickingRestHandoverDto.setMessage("只能操作待交接的单据");
//                return pickingRestHandoverDto;
//            }
//        }
        return pickingRestHandoverDto;
    }

    /**
     * 提交审核
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitReview(Long id) {
        //获取单据数据
        SalesReturn salesReturn = salesReturnMapper.selectById(id);
        if (salesReturn.getStatus() == 1) {
            salesReturn.setStatus(2);

            SysWorkbenchAuditAgentDubboVo sysWorkbenchAuditAgentDubboVo = new SysWorkbenchAuditAgentDubboVo();
            sysWorkbenchAuditAgentDubboVo.setDocConfig("warehouse:warehousing:saleReturn:review");
            sysWorkbenchAuditAgentDubboVo.setReceiptName("销售退货");
            sysWorkbenchAuditAgentDubboVo.setReceiptNumber(salesReturn.getReceiptNo());
            sysWorkbenchAuditAgentDubboVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentDubboVo.setReceiptContent("有单据待审核,请及时审核");

            remoteWorkbenchMessageService.insertAuditAgent(sysWorkbenchAuditAgentDubboVo);
            return salesReturnMapper.updateById(salesReturn) > 0;
        } else {
            throw new GlobalException("只能对状态为“待提交”的单据进行提交操作");
        }
    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteReview(Long id) {
        //获取单据数据
        SalesReturn salesReturn = salesReturnMapper.selectById(id);
        if (salesReturn.getStatus() == 2) {
            salesReturn.setStatus(1);
            //删除审核代办
            remoteWorkbenchMessageService.deleteDoc(salesReturn.getReceiptNo(), "销售退货");
            return salesReturnMapper.updateById(salesReturn) > 0;
        } else {
            throw new GlobalException("只能对状态为“待审核”的单据进行撤销操作");
        }
    }

    /**
     * 审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    public boolean saleReturnReview(OrderReviewVo orderReviewVo) throws Exception {
        SalesReturn salesReturn = salesReturnMapper.selectById(orderReviewVo.getId());
        if (salesReturn.getStatus() == 2 || salesReturn.getStatus() == 3) {
            String perms = "warehouse:warehousing:saleReturn:review";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = salesReturn.getReceiptNo();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = LoginHelper.getUserId();
            SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
            sysAuditHistoryVo.setPerms(perms);
            sysAuditHistoryVo.setModuleType(3);
            sysAuditHistoryVo.setAuditState(isAdopt);
            sysAuditHistoryVo.setAuditRemarks(auditRemarks);
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setUserId(userId);
            int data = remoteReviewService.getSequence(sysAuditHistoryVo);
            if (data == 0) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    salesReturn.setStatus(5);
                    salesReturn.setReviewTime(new Date());
                    //回传待到货数据到采购计划
//                    ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
//                    procurementPlanDetail.setStatus(2);
//                    procurementPlanDetailMapper.updateById(procurementPlanDetail);

                    //修改审核代办状态
                    remoteWorkbenchMessageService.updateStatus(3, salesReturn.getReceiptNo(), "销售退货");

                    return salesReturnMapper.updateById(salesReturn) > 0;
                } else if (data == 2) {
                    salesReturn.setStatus(3);
                    salesReturn.setReviewTime(new Date());
                    return salesReturnMapper.updateById(salesReturn) > 0;
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    salesReturn.setStatus(4);
                    salesReturn.setReviewTime(new Date());
                    SysWorkbenchAuditAgentDubboVo sysWorkbenchAuditAgentDubboVo = new SysWorkbenchAuditAgentDubboVo();
                    sysWorkbenchAuditAgentDubboVo.setDocConfig("warehouse:warehousing:saleReturn:review");
                    sysWorkbenchAuditAgentDubboVo.setReceiptName("销售退货");
                    sysWorkbenchAuditAgentDubboVo.setReceiptNumber(salesReturn.getReceiptNo());
                    sysWorkbenchAuditAgentDubboVo.setStatus(2);//待处理
                    sysWorkbenchAuditAgentDubboVo.setPassFlag("1");
                    sysWorkbenchAuditAgentDubboVo.setCreateName(LoginHelper.getUsername());
                    sysWorkbenchAuditAgentDubboVo.setReceiptContent("有单据未通过,请及时查看");

                    remoteWorkbenchMessageService.insertAuditAgent(sysWorkbenchAuditAgentDubboVo);

                    return salesReturnMapper.updateById(salesReturn) > 0;
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }
    }


//    /**
//     * 销售退货品质检验回传修改数据(品质审核时fegin调用)
//     *
//     * @param updateStatusByQualityVo
//     * @return
//     */
//    @Override
//    public boolean updateStatusByQuality(UpdateStatusByQualityVo updateStatusByQualityVo) {
//        Long menuId = feignService.getIdByMenuName("销售退货");
//        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
//        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
//        //获取销售退货及对应明细信息
//        SalesReturn salesReturn = salesReturnMapper.selectOne(new QueryWrapper<SalesReturn>().lambda().eq(SalesReturn::getReceiptNo, updateStatusByQualityVo.getAssociatedNo()));
//
//        List<SalesReturnDetail> salesReturnDetails = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
//        //如果单据状态为待检验
//        if (salesReturn.getStatus() == 3) {
//            //如果配置了交接
//            if (sysDocument.getDocHandoverMark() == 1) {
//                salesReturn.setStatus(4);
//                for (SalesReturnDetail entity : salesReturnDetails) {
//                    entity.setStatus(2);
//                }
//            } else {
//                for (SalesReturnDetail entity : salesReturnDetails) {
//                    entity.setStatus(3);
//                }
//                salesReturn.setStatus(5);
//            }
//        }
//        if (salesReturnDetails.size() > 0) {
//            salesReturnDetailService.updateBatchById(salesReturnDetails);
//        }
//
//        return updateById(salesReturn);
//    }

}
